package com.lw.sbdemo2.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.lw.sbdemo2.common.base.BaseController;
import com.lw.sbdemo2.common.constant.TkConstants;
import com.lw.sbdemo2.common.utils.IdUtils;
import com.lw.sbdemo2.common.utils.ValidUtil;
import com.lw.sbdemo2.common.vo.PageInfo;
import com.lw.sbdemo2.common.web.anno.Required;
import com.lw.sbdemo2.common.web.anno.ResultController;
import com.lw.sbdemo2.entity.TkExamProductDetail;
import com.lw.sbdemo2.entity.TkExamProductMaster;
import com.lw.sbdemo2.entity.TkUserErrorExamDetail;
import com.lw.sbdemo2.mapper.TkExamProductDetailMapper;
import com.lw.sbdemo2.mapper.TkUserErrorExamDetailMapper;
import com.lw.sbdemo2.mapper.TkUserInfoMapper;
import com.lw.sbdemo2.service.TkExamProductDetailService;
import com.lw.sbdemo2.service.TkExamProductMasterService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.beans.Beans;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>标题: 试卷商品主表服务 - 请求控制层</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2019</p>
 * <p>公司: 山人行工作室</p>
 *
 * @version: 1.0
 * @author: LinWang
 * @date 2019-4-14
 */
@ResultController
@Api(description = "TkExamProductMasterController", tags = {"试卷商品主表服务"})
@RequestMapping(value = "/tkExamProductMaster")
public class TkExamProductMasterController extends BaseController {

    @Autowired
    private TkExamProductMasterService tkExamProductMasterService;

    @Autowired
    private TkExamProductDetailService tkExamProductDetailService;

    @Autowired
    private TkExamProductDetailMapper tkExamProductDetailMapper;

    @Autowired
    private TkUserErrorExamDetailMapper tkUserErrorExamDetailMapper;

    @Autowired
    private TkUserInfoMapper tkUserInfoMapper;

    @ApiOperation(value = "获取试卷商品主表列表")
    @GetMapping("")
    public List<TkExamProductMaster> findList(TkExamProductMaster tkExamProductMaster) {

        if (ValidUtil.isNotEmptyAndNull(tkExamProductMaster.getSubUnits())){
            tkExamProductMaster.setSubUnitArr(tkExamProductMaster.getSubUnits().split(","));
        }

        return tkExamProductMasterService.findList(tkExamProductMaster);
    }

    @ApiOperation(value = "获取试卷商品主表列表（分页）", response = PageInfo.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "query", value = "关键词", dataType = "string"),
            @ApiImplicitParam(name = "pageNum", value = "当前页码", required = true, dataType = "int"),
    })
    @GetMapping(value = "/page")
    public PageInfo<TkExamProductMaster> page(String query, @Required("pageNum") PageInfo pageInfo, TkExamProductMaster tkExamProductMaster) {
        return tkExamProductMasterService.findListPage(query, pageInfo, tkExamProductMaster);
    }

    @ApiOperation(value = "获取试卷商品主表详细信息", notes = "根据url的id来获取试卷商品主表详细信息")
    @ApiImplicitParam(name = "id", value = "试卷商品主表ID", required = true, dataType = "String")
    @GetMapping("/{id}")
    public TkExamProductMaster get(@PathVariable String id, String flag, String userId, String role, String classId, String questionId) throws Exception {

        TkExamProductMaster tkExamProductMaster = tkExamProductMasterService.getById(id);

        if (tkExamProductMaster != null) {
            TkExamProductDetail tkExamProductDetail = new TkExamProductDetail();
            tkExamProductDetail.setExamId(id);
            //展示模式需要错题集
            if (TkConstants.EXAM_FLAG_SHOW.equals(flag)) {
                tkExamProductDetail.setFlag(flag);
                tkExamProductDetail.setUserId(userId);
            }
            List<TkExamProductDetail> tkExamProductDetails = new ArrayList<>();

            if (ValidUtil.isNotEmptyAndNull(role)) {
                tkExamProductDetail.setRole(role);
            }

            if (TkConstants.EXAM_FLAG_GAO.equals(role)) {
                //错误超过多少算高频错题，默认5
                int errorNum = 1;
                if (ValidUtil.isNotEmptyAndNull(classId)) {
                    //获取班级答题人数，错误超过分之30为高频错题
                    Integer classNum = tkExamProductDetailMapper.getClassNum(classId, id);
                    if (ValidUtil.isEmptyAndNull(userId) && classNum > 1) {
                        errorNum = new Double(classNum * 0.5).intValue();
                    }
                }
                tkExamProductDetail.setClassId(classId);
                tkExamProductDetail.setErrorNum(errorNum);
                tkExamProductDetails = tkExamProductDetailMapper.findListGao(tkExamProductDetail);
            } else {
                if(ValidUtil.isNotEmptyAndNull(questionId)){
                    TkExamProductDetail temp = tkExamProductDetailService.getById(questionId);
                    tkExamProductDetails.add(temp);
                    List<TkExamProductDetail>  allList =
                            tkExamProductDetailService.findList(TkExamProductDetail.builder().examId(tkExamProductDetail.getExamId()).build());
                    tkExamProductMaster.setAllList(allList);
                } else {
                    tkExamProductDetails = tkExamProductDetailService.findList(tkExamProductDetail);
                    //如果是学生错题的话，计算该题目题号
                    if (TkConstants.EXAM_FLAG_STUDENT.equals(role)) {
                        TkExamProductDetail tkExamProductDetailTemp = TkExamProductDetail.builder().examId(id).build();
                        List<TkExamProductDetail> tkProductDetail = tkExamProductDetailService.findAllList(tkExamProductDetailTemp);
                        tkExamProductDetails.forEach(item ->{
                            String questionId1 = item.getQuestionId();
                            int i = 0;
                            for (TkExamProductDetail temp : tkProductDetail) {
                                i++;
                                if (Objects.equals(questionId1 , temp.getQuestionId())) {
                                    item.setQuestionErrorNumber(i);
                                }
                            }
                        });
                    }
                }
            }

            tkExamProductMaster.setQuesList(tkExamProductDetails);

            Map<String, List<TkExamProductDetail>> quesMap = new HashMap<>(16);
            for (TkExamProductDetail examProductDetail : tkExamProductDetails) {
                String type = examProductDetail.getQuestionType();
                if (quesMap.containsKey(type)) {
                    quesMap.get(type).add(examProductDetail);
                } else {
                    List<TkExamProductDetail> tempList = new ArrayList<>();
                    tempList.add(examProductDetail);
                    quesMap.put(type, tempList);
                }
            }
            tkExamProductMaster.setQuesMapStr(JSON.toJSONString(quesMap));

            //展示模式需要错题集
            if (TkConstants.EXAM_FLAG_SHOW.equals(flag)) {
                TkUserErrorExamDetail tkUserErrorExamDetail = TkUserErrorExamDetail.builder().examId(id).userId(userId).build();
                List<TkUserErrorExamDetail> tkUserErrorExamDetailList = tkUserErrorExamDetailMapper.findList(tkUserErrorExamDetail);
                Map<String, String> errorMap = new HashMap<>(16);
                for (TkUserErrorExamDetail item : tkUserErrorExamDetailList) {
                    errorMap.put(item.getQuestionId(), item.getErrorAnswer());
                }
                tkExamProductMaster.setErrorMap(errorMap);
            }
        }

        return tkExamProductMaster;
    }

    @ApiOperation(value = "创建试卷商品主表")
    @PostMapping("/insert")
    public void insert(TkExamProductMaster tkExamProductMaster) {

        String examType = tkExamProductMaster.getExamType();
        List<String> examTypeArr = JSONArray.parseArray(examType, String.class);
        List<TkExamProductMaster> resultArr = new ArrayList<>();

        if (!CollectionUtils.isEmpty(examTypeArr)) {
            //对不同类型的试题数据处理
           resultArr = examTypeArr.stream().map(item -> {
               TkExamProductMaster temp = new TkExamProductMaster();
               try {
                   temp = (TkExamProductMaster)BeanUtils.cloneBean(tkExamProductMaster);
               } catch (IllegalAccessException e) {
                   e.printStackTrace();
               } catch (InstantiationException e) {
                   e.printStackTrace();
               } catch (InvocationTargetException e) {
                   e.printStackTrace();
               } catch (NoSuchMethodException e) {
                   e.printStackTrace();
               }
               temp.setExamType(item);
               temp.setCreatedTime(new Date());
               temp.setExamId(IdUtils.uuid() + item);
                return temp;
            }).collect(Collectors.toList());
            //批量插入到数据库
            resultArr.forEach(temp ->{
                tkExamProductMasterService.insert(temp);
            });
        }

    }

    @ApiOperation(value = "更新试卷商品主表详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "试卷商品主表ID", required = true, paramType = "query", dataType = "String")
    })
    @PostMapping("/update")
    public void update(TkExamProductMaster tkExamProductMaster) {
        tkExamProductMaster.setModifiedTime(new Date());
        tkExamProductMasterService.update(tkExamProductMaster);
    }

    @ApiOperation(value = "导入试卷商品主表细表详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "试卷商品主表ID", required = true, paramType = "query", dataType = "String")
    })
    @PostMapping("/importExcel")
    public void importExcel(String examId, MultipartFile uploadFile) throws Exception {
        tkExamProductMasterService.importExcel(examId, uploadFile.getOriginalFilename(), uploadFile.getInputStream());

    }

    @ApiOperation(value = "删除试卷商品主表", notes = "删除试卷商品主表")
    @ApiImplicitParam(name = "id", value = "试卷商品主表ID", required = true, paramType = "query", dataType = "String")
    @PostMapping("/delete")
    public void deleteTkExamProductMaster(TkExamProductMaster tkExamProductMaster) throws Exception {

        tkExamProductMasterService.delete(tkExamProductMaster);
        tkExamProductMasterService.deleteDetail(tkExamProductMaster);
    }

}
